package com.ebus.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.stereotype.Controller;

import com.ebus.vo.BusLine;

@Controller("/busLineAction")
public class BusLineAction extends BaseAction {
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public ActionForward getBusLine(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			response.setCharacterEncoding("UTF-8");
			Map<String, Object> paramMap = getParameterMap(request);
			
			//List<Map<Object,Object>> buslList= this.busLineService.getResultMap(paramMap.get("busNumber").toString());
			List<BusLine> buslList= this.busLineService.getBusLineList(paramMap.get("busNumber").toString());
			
			JSONArray buslineJsonArray = JSONArray.fromObject(buslList);
			response.getWriter().write(buslineJsonArray.toString());
		} catch (IOException e) {
			response.getWriter().write("服务器异常！");
			e.printStackTrace();
		}
		return mapping.findForward("");
	}

	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map getParameterMap(HttpServletRequest request) {
		// 参数Map
		Map properties = request.getParameterMap();
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}
}
